package org.bing.engine.utility.helper;

import java.util.HashMap;
import java.util.Map;

public class MulValueThreadLocal {

	private final static MulValueThreadLocal instance = new MulValueThreadLocal();
	private final static ThreadLocal<Map<String, Object>> local = new ThreadLocal<Map<String, Object>>();

	private MulValueThreadLocal() {

	}

	/* use map, be care memory leak */
	public static MulValueThreadLocal newInstance() {
		return instance;
	}

	public Object get(String key) {
		Map<String, Object> map = getValueContainer();
		return map.get(key);
	}

	public void set(String key, Object value) {
		Map<String, Object> map = getValueContainer();
		map.put(key, value);
	}

	public Object clear(String key) {
		Map<String, Object> map = getValueContainer();
		if (key != null) {
			return map.remove(key);
		} else {
			return null;
		}
	}

	public void clear() {
		local.set(null);
	}

	private Map<String, Object> getValueContainer() {
		Map<String, Object> map = local.get();
		if (map != null) {
			return map;
		} else {
			map = new HashMap<String, Object>();
			local.set(map);
		}
		return map;
	}
}
